import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import { Link, useNavigate } from "react-router-dom";
import {
  Row,
  Col,
  Button,
  Space,
  message,
  Table,
  Popconfirm,
  Layout,
  Tooltip,
  Progress,
  Modal,
  Form,
  Input,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
} from "@ant-design/icons";
import moment from "moment";
import Reactordrawer from "./Reactordrawer";
import { ITStore } from "../../store";
import { ITColumns, ITDesinger } from "../../store/interfaces";

type TProp = {
  store: ITStore;
};

interface ITCopyModalProp extends TProp {
  isShow: boolean;
  close: () => void;
  data: ITDesinger;
}

interface ITFormValues {
  name: string;
  desc: string;
}

const { Content } = Layout;

const CopyModal: FC<ITCopyModalProp | any> = inject("store")(
  observer(({ store, isShow, close, data }: ITCopyModalProp) => {
    const {
      languageStore: { lang },
      designerStore: { copyDesigner, getAllDesigner },
    } = store;

    const [form] = Form.useForm();

    const [copyLoading, setCopyLoading] = useState(false);

    const closeModal = () => {
      form.resetFields();
      close();
    };

    const onFinish = async (values: ITFormValues) => {
      setCopyLoading(true);
      const res = await copyDesigner({ ...values, designerId: data.id });
      setCopyLoading(false);
      if (!res) {
        getAllDesigner();
        message.success(lang["langdeletesuccess"]);
        close();
      } else {
        // 登录失败提示
        const { msg } = res;
        if (msg === "duplicate") {
          message.error(lang["langcopydup"]);
        }
      }
    };

    return (
      <Modal
        title={`${lang["langcopy"]} ${data?.name}`}
        open={isShow}
        onOk={() => {
          form.submit();
        }}
        onCancel={closeModal}
        destroyOnClose={true}
        confirmLoading={copyLoading}
      >
        <Form
          name="copyProjectForm"
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={onFinish}
        >
          <Form.Item
            label={lang["langprojectname"]}
            name="name"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label={lang["langdescription"]} name="desc">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

const DesignerTableList: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      designerStore: {
        getAllDesigner,
        allDesignerLoading,
        allDesigner,
        delDesignerLoading,
        delDesigner,
        changeShowDesingerDetail,
        changeCurrentWorkbench
      },
      userStore: { getUserInfo },
    } = store;

    const navigate = useNavigate();

    const [delData, setDelData] = useState<ITDesinger | null>(null);

    const [viewData, setViewData] = useState<ITDesinger | null>(null);

    const [showCopyModal, setShowCopyModal] = useState<boolean>(false);

    const [copyInfo, setCopyInfo] = useState<ITDesinger>();

    const [tableColumn, setTableColumn] = useState<any>([])

    const delconfirm = async (data: ITDesinger) => {
      setDelData(data);
      const { id } = data;
      const result = await delDesigner({ id });
      if (!result) {
        getAllDesigner();
        message.success(lang["langdeletesuccess"]);
        setDelData(null);
      }
    };

    const viewDesign = (record: ITDesinger) => {
      setViewData(record);
      changeShowDesingerDetail(true);
    };

    const copyDesign = (record: ITDesinger) => {
      setCopyInfo(record);
      setShowCopyModal(true);
    };

    const closeCopyModal = () => {
      setShowCopyModal(false);
    };

    const columns: ITColumns[] = [
      {
        title: lang["langprojectname"],
        dataIndex: "name",
        key: "name",
      },
      {
        title: lang["langprogress"],
        dataIndex: "step",
        key: "step",
        render: (step: number) => {
          return <Progress percent={(step / 4) * 100} steps={4} />;
        },
      },
      {
        title: lang["langdescription"],
        dataIndex: "desc",
        key: "desc",
      },

      {
        title: lang["langcreationtime"],
        dataIndex: "createdTime",
        key: "createdTime",
        render: (minsec: number) => {
          return moment(minsec).format("YYYY-MM-DD HH:mm");
        },
      },
      {
        title: lang["langupdatetime"],
        dataIndex: "updateTime",
        key: "updateTime",
        render: (minsec: number) => {
          return moment(minsec).format("YYYY-MM-DD HH:mm");
        },
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        align: "center",
        width: "6%",
        render: (_: string, record: ITDesinger) => (
          <Space>
            <Tooltip title={lang["langview"]}>
              <Button
                type="link"
                icon={<EyeOutlined />}
                disabled={record.step < 4}
                onClick={() => {
                  viewDesign(record);
                }}
              />
            </Tooltip>
            <Tooltip title={lang["langedit"]}>
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => {
                  navigate(`/designer/add/${record.id}`);
                }}
              />
            </Tooltip>
            <Tooltip title={lang["langcopy"]}>
              <Button
                type="link"
                icon={<CopyOutlined />}
                onClick={() => {
                  copyDesign(record);
                }}
              />
            </Tooltip>
            <Popconfirm
              placement="top"
              title={lang["langconfirmdel"]}
              onConfirm={() => {
                delconfirm(record);
              }}
            >
              <Tooltip title={lang["langdelete"]}>
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                  loading={delData?.id === record.id && delDesignerLoading}
                />
              </Tooltip>
            </Popconfirm>
          </Space>
        ),
      },
    ];

    useEffect(() => {
      getAllDesigner();

      const userInfo = getUserInfo();

      const { privilege } = userInfo || {};
      if (privilege === "admin") {
        columns.splice(3, 0, {
          title: lang["langusername"],
          dataIndex: "userInfo",
          key: "userInfo",
          render: (info: any) => {
            return info.account;
          },
        });
      }
      setTableColumn(columns)
      changeCurrentWorkbench(null)
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
      <>
        <Table
          dataSource={allDesigner}
          columns={tableColumn}
          bordered
          loading={allDesignerLoading}
        />
        <Reactordrawer designerId={viewData?.id} />
        <CopyModal
          isShow={showCopyModal}
          close={closeCopyModal}
          data={copyInfo}
        />
      </>
    );
  })
);

// 搜索和新增按钮组件
const SearchAddComp: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
    } = store;

    return (
      <Row style={{ marginBottom: 20 }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Space wrap style={{ float: "right" }}>
            <Link to={"/designer/add"}>
              <Button type="primary" icon={<PlusOutlined />}>
                {lang["langcreateproject"]}
              </Button>
            </Link>
          </Space>
        </Col>
      </Row>
    );
  })
);

const DesignerList = () => {
  return (
    <Content className="mainLayout">
      {/* 搜索和新增按钮组件 */}
      <SearchAddComp />

      {/* 实验设计列表 */}
      <DesignerTableList />
    </Content>
  );
};

export default DesignerList;
